import datetime
import os
from globelly import *
from log import write_log

def __today(): # 今天日期
    result=datetime.date.today()
    date = str(result)
    # print(date,type(date))
    return date

def __lastday():    # 昨天日期
    now_time = datetime.datetime.now()
    last_time = now_time + datetime.timedelta(days=-1)
    lastday = str(last_time).split(' ')[0]
    return lastday

def __get_info_in_url(url):  # 通过URL提取 大版本，小版本，库，CPU架构四个信息  返回值：含有这四个信息的列表
    mod_debug_info = 0
    if mod_debug_info:
        url = "https://update.cs2c.com.cn/NS/V10/V10SP1/os/adv/lic/base/x86_64/Packages/"

    info = []
    info.append(url.split('/')[4])
    info.append(url.split('/')[5])
    info.append(url.split('/')[-4])
    info.append(url.split('/')[-3])

    if mod_debug_info:
        print("",
        "大版本:   {}\n".format(info[0]),
        "小版本：  {}\n".format(info[1]),
        "库：     {}\n".format(info[2]),
        "CPU架构：{}".format(info[3]))

    return info

def url_to_todayandlastpack(url):
    # 获取今日文件数据地址, 和昨日文件数据地址
    info = __get_info_in_url(url)
    todayfilepath = WorkDir + 'databases/{}/{}/{}/{}/{}'.format(__today(), info[0], info[1], info[2], info[3])
    lastdayfilepath = WorkDir + 'databases/{}/{}/{}/{}/{}'.format(__lastday(), info[0], info[1], info[2], info[3])
    print('---->todaypath: ',todayfilepath)
    print('---->lastdaypath: ',lastdayfilepath)
    # 记录路径数据输出到日志
    write_log('diff',"源地址: {}/{}/{}/{}".format(info[0], info[1], info[2], info[3]))
    # 读取今天所有包数据,和昨天所有包数据进行对比
    today = []
    lastday = []
    if not os.path.exists(lastdayfilepath):
        write_log('diff',"    Notice ----> 昨日数据不存在")
    else:
        # 读取包列表
        with open(todayfilepath, 'r', encoding='UTF-8') as f:
            for name in f.read().split('\n'):
                if 'rpm' in name:
                    today.append(name.lstrip().rstrip())
        with open(lastdayfilepath, 'r', encoding='UTF-8') as g:
            for name in g.read().split('\n'):
                if 'rpm' in name:
                    lastday.append(name.lstrip().rstrip())
    return today,lastday


def diff_packages(today, lastday):
    TodayMore = []
    LastMore = []
    # 对比找到数据包差异
    TodayMore = today.copy()
    LastMore = lastday.copy()
    diff = []
    for name in today:
        if name in lastday:
            TodayMore.remove(name)
            LastMore.remove(name)
        else:
            diff.append(name)
    print('增加:', TodayMore)
    print('减少:', LastMore)
    # 根据差异写report
    if not TodayMore and not LastMore:
            write_log('diff',"    Notice ----> 昨日未变更数据")
    else:
        for i in TodayMore:
            write_log('diff','    Add: {}'.format(i))
        for j in LastMore:
            write_log('diff','    Remove: {}'.format(j))





def __write_logfile(url):
    info = __get_info_in_url(url)
    reportpath = WorkDir + 'report'
    return reportpath
